package middleware.p2p.log;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import middleware.p2p.log.XmlHashtableType.XmlHashtableValue;

/**
 * 	Classe adapter che si occupa di eseguire la mappatura di una hash table contenente interi e avente come chiavi
 * 	delle stringhe sul tipo {@link XmlHashtableType} serializzabile con JAXB.
 */
public class XmlHashtableAdapter extends XmlAdapter<XmlHashtableType, Hashtable<String,Integer>> {
	@Override
	public XmlHashtableType marshal(Hashtable<String,Integer> v) throws Exception {
		Enumeration<String> keys=v.keys();
		XmlHashtableType hashrep=new XmlHashtableType();
		while (keys.hasMoreElements()) {
			String key=keys.nextElement();
			hashrep.vc_element.add(new XmlHashtableType.XmlHashtableValue(key, (Integer)v.get(key)));
		}
		return hashrep;		
	}

	@Override
	public Hashtable<String,Integer> unmarshal(XmlHashtableType v) throws Exception {
		Hashtable<String,Integer> localTable=new Hashtable<String, Integer>();
		Iterator<XmlHashtableValue> it=v.vc_element.listIterator();
		while (it.hasNext()) {
			XmlHashtableValue cvalue=it.next();
			localTable.put(cvalue.cid, cvalue.value);
		}
		return localTable;
	}	
}
